/**
 * 
 */
package com.tw.trips.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.FlagTerm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.tw.trips.processor.IrctcItineraryProcessor;

/**
 * @author M1005264
 *
 */
@Service
public class EmailClient {

	@Autowired
	private IrctcItineraryProcessor processor;

	private Properties props;

	private static final String EMAIL_CONFIG_FILE ="email.properties"; 

//	@Async
	public void pullEmails(){
		System.out.println("Starting to Pull Email");
		loadConfig();
		Session mailSession = Session.getDefaultInstance(props, null);
		try {
			Store store = mailSession.getStore("imaps");
			store.connect(props.getProperty("email.host"), props.getProperty("email.user"), props.getProperty("email.pass"));
			FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
			Folder folder = store.getFolder("INBOX");
			folder.open(Folder.READ_WRITE);

			Message messages[] = folder.search(ft);

			if(messages != null){
				for(int i = 0 ; i < messages.length; i ++){
					processMail(messages[i]);
				}
			}
			folder.close(false);
			store.close();
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Finished to Pull Email");
	}

	private void processMail(Message mail) {
		try {
			MimeMultipart message = (MimeMultipart) mail.getContent();
			BodyPart bodyPart = message.getBodyPart(0);
			String data = convertStreamToString(bodyPart.getInputStream());
			processor.process(mail.getFrom()[0].toString(),data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{

		}
	}

	private String convertStreamToString(InputStream is) throws IOException {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\n");
		}
		is.close();
		System.out.println(sb.toString());
		return sb.toString();

	}

	private void loadConfig() {
		if(props == null){
			InputStream is = IrctcStationCodes.class.getClassLoader().getResourceAsStream(EMAIL_CONFIG_FILE);  
			props = new Properties();  
			try {
				props.load(is);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
